<template>
  <!-- 签名组件 -->
  <div>
    <el-card class="qianming-container" body-style="padding:0px">
      <vue-esign
        ref="esign"
        :isCrop="isCrop"
        :width="700"
        :height="500"
        :lineWidth="lineWidth"
        :lineColor="lineColor"
        :format="'image/png'"
        :bgColor.sync="bgColor"
      ></vue-esign>
      <div class="contro-container">
        <el-button type="danger" @click="handleReset">清空画板</el-button>
        <el-button type="primary" @click="handleGenerate">确认签名</el-button>
      </div>
    </el-card>
  </div>
</template>
    
  <script>
import vueEsign from "vue-esign";
import { uploadFile } from "@/api/thridParty/index.js";
export default {
  components: { vueEsign },
  name: "Qianming",
  data() {
    return {
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "",
      resultImg: "",
      isCrop: false,
    };
  },
  methods: {
    //清空画板..
    handleReset() {
      this.$refs.esign.reset();
      this.resultImg = "";
    },
    //生成签名图片..
    handleGenerate() {
      this.$refs["esign"]
        .generate()
        .then((res) => {
          this.resultImg = res; // 得到了签字生成的base64图片
          // this.$emit("setsignin", res);
          // 也可以转换成在线地址
          this.dataURLtoFile(res);
        })
        .catch((err) => {
          //  没有签名，点击生成图片时调用
          this.$message({
            message: " 请填写签名！",
            type: "warning",
          });
        });
    },

    //将base64 上传到服务器，转换成在线地址
    dataURLtoFile(res) {
      const file = this.base64ToFile(res);
      let formData = new FormData();
      formData.append("file", file);
      // 上传图片
      uploadFile(formData).then((result) => {
        this.$emit("setsignin", result);
      });
    },
    base64ToFile(data) {
      // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
      let binary = atob(data.split(",")[1]);
      let mime = data.split(",")[0].match(/:(.*?);/)[1];
      let array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      let fileData = new Blob([new Uint8Array(array)], {
        type: mime,
      });
      let file = new File([fileData], `${new Date().getTime()}.png`, {
        type: mime,
      });
      return file;
    },
  },
};
</script>
    
  <style scoped>
button {
  height: 40px;
}
.contro-container {
  width: 600px;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  background-color: #d3d3d3;
  position: absolute;
  bottom: 0px;
}
.qianming-container {
  width: 600px;
  height: 350px;
  margin: 10px auto;
  position: relative;
}
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-top: 20px;
}
</style>
    